<?php

namespace app\api\service\tieba;



use app\api\model\tieba\User as TiebaLink;
use app\api\service\token\LoginToken;
use think\Db;
use think\Exception;
use app\lib\exception\tieba\TiebaException;

class OperationService
{
    private static $instance;
    protected $appId = "0587bb44";
    protected $apiKey = '8b64946a4539294e3ce5d5ba900d06d8';
    protected $secretKey = 'MTE3MGM3YjdjMzY2ZGFhNjc3ZTJhNjJj';
    public static function getInstance(): OperationService
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function getTiebaList(){
        $pageSize = $params['pageSize'] ?? 50;
        $result = TiebaLink::field("*")->paginate($pageSize);
        return $result;
    }

    public function tiebaImport($params){
        DB::startTrans();
        try {
            #写入数据库
            foreach ($params["excel"] as $val) {
                $add = [
                    "link"=>$val["link"],
                    "area"=>$val["area"],
                ];
                $exists = TiebaLink::where('link',$val["link"])->findOrEmpty();
                if($exists->isEmpty()){
                    TiebaLink::create($add);
                }
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new TiebaException([
                'msg' => '导表失败',
                'error_code' => 20002
            ]);
        }
    }

    public function tiebaUpload($params){
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
        DB::startTrans();
        try {
                $data = [
                    "title" => $params["title"],
                    "app_id" => $params["app_id"],
                    "type" => $params["type"],
                    "pub_time" => $params["pub_time"],
                    "get_time" => date("Y-m-d H:i:s"),
                    "content_id" => $params["content_id"],
                    "uid" => $uid,
                    "data" => json_encode($params["data"],JSON_UNESCAPED_UNICODE),
                    "status" => 1
                ];
                TiebaLink::where("id",$params["id"])->update($data);
                // 提交事务
                Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new TiebaException([
                'msg' => '填入失败',
                'error_code' => 20002
            ]);
        }
    }

    public function distribute(){
        $current_time = date("Y-m-d H:i:s");
        $get_time = date("Y-m-d H:i:s", time() - 60);
        $result = [];
        $x = 0;
        DB::startTrans();
        $appids = [];
        $count = 0;
        try {
            $app_id__arr_query = TiebaLink::where("get_time",'>',$get_time);
            $app_id_arr = $app_id__arr_query
                ->distinct(true)
                ->field('app_id')
                ->select()->toArray();
            $temporary = [];
            foreach ($app_id_arr as $val){
                $temporary[] = $val['app_id'];
            }
            $query = TiebaLink::where("status",1)
                ->where("pub_time", '<',$current_time);
//                ->whereNotIn("app_id",$temporary);
            $list = $query->with('account')
                ->orderRand()
//                ->order("source_time asc")
                ->lock(true)
                ->limit(10)->select();
            if(!$list->isEmpty()){
                $ids = [];
                foreach ($list as $item){
                    if(!in_array($item['app_id'],$appids)){
                        $appids[] = $item['app_id'];
                        $result[] = $item;
                        $ids[] = $item['id'];
                        $count++;
                    }
                }
                if (!empty($ids)){
                    TiebaLink::whereIn('id',$ids)->update([
                        'status' => 2,
                        'get_time'=>date("Y-m-d H:i:s"),
                        'update_time'=>date("Y-m-d H:i:s")
                    ]);
                }

            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
        }

        return $result;
    }

    public function write($params){
        $Event = TiebaLink::where('id',$params['id'])->findOrEmpty();
        if (!$Event->isEmpty()){
            $Event->save($params);
        }
        return true;
    }
    public function rewriting($params){
        $headers = array(
            "Content-type:application/json;",
            "Accept:application/json",
            "host:api.xf-yun.com"
        );
        $host = "api.xf-yun.com";
        $url = "https://api.xf-yun.com/v1/private/se3acbe7f";
        $patch = "/v1/private/se3acbe7f";
        $time = gmdate('D, d M Y H:i:s') . ' GMT';
        $signature_origin = "host: ".$host."\n";
        $signature_origin .= "date: ".$time."\n";
        $signature_origin .= "POST ".$patch." HTTP/1.1";
        $signature_sha = hash_hmac('sha256', $signature_origin, $this->secretKey,true);
        $signature = base64_encode($signature_sha);
        $authorization_origin = 'api_key="' . $this->apiKey . '", algorithm="hmac-sha256", ';
        $authorization_origin .= 'headers="host date request-line", signature="' . $signature . '"';
        $authorization = base64_encode($authorization_origin);
        $url .= '?' . 'authorization=' . $authorization . '&date=' . urlencode($time) . '&host='.$host;
        $data = [
            "header" => [
                "app_id" => $this->appId,
                "status" => 3,
            ],
            "parameter" => [
                "se3acbe7f" => [
                    "level" => "<L".$params["level"].">",
                    "result" =>[
                        "encoding"=> "utf8",
                        "compress" => "raw",
                        "format" => "json"
                    ]
                ]
            ],
            "payload" => [
                "input1"=>[
                    "encoding" => "utf8",
                    "compress"=> "raw",
                    "format"=> "plain",
                    "status"=> 3,
                    "text"=> base64_encode($params["content"])
                ]
            ]
        ];
        $data = json_encode($data);
        $response = curlPost($url,$data,$headers);
        if ($response["header"]["code"] == 0){
            $res = base64_decode($response["payload"]["result"]["text"]);
            $data = json_decode($res)[0][0];
            return $data;
        }
        return $response;
    }

}
